<?php

// +----------------------------------------------------------------------
// | H1CMS © OpenSource CMS
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2016 http://www.h1cms.com All rights reserved.
// | Copyright (c) 2014-2016 嘉兴领格信息技术有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Allen <allen@lg4.cn>
// +----------------------------------------------------------------------

function get_roles_text() {
    $roles = h1cms\system\Auth::userRoles();
    $roles = db()->quote($roles);
    $role_pairs = db_fetch_pairs('roles', ['id', 'title'], "id in ({$roles})");
    return $role_pairs;
}

function maybe_change_username(&$user, $username, $email) {
    if ($user->username != $username) {
        if (__username_is_exists($username)) {
            return redirect('/users/')->withFlash('error', '【' . $username . '】用户名已经存在');
        }else{
            $user->username = $username;
        }        
    }
    if ($user->email != $email) {
        if (__email_is_exists($email)) {
            return redirect('/users/')->withFlash('error', '【' . $email . '】Email地址已经存在');
        }else{
            $user->email = $email;
        }
    }
    return NULL;
}

function __username_is_exists($username) {
    $_username = db_query_value("select username from {users} where username=:username", ['username'=>$username]);
    return ($_username == $username);
}

function __email_is_exists($email) {
    $_email = db_query_value("select email from {users} where email=:email", ['email'=>$email]);
    return ($_email == $email);
}
